package main

import (
	"crypto/sha256"
	"fmt"
)

// 计算hash
func calHash(data []byte) []byte {
	hash := sha256.Sum256(data)
	return hash[:]
}

// 创建MerkleTree节点
type MerkleNode struct {
	hash       []byte
	leftChild  *MerkleNode
	rightChild *MerkleNode
}

// 创建叶子节点
func NewMerkleLeaf(data []byte) *MerkleNode {
	return &MerkleNode{
		hash: calHash(data),
	}
}

// 创建父节点
func NewMerkleParent(left, right *MerkleNode) *MerkleNode {
	parent := &MerkleNode{
		leftChild:  left,
		rightChild: right,
	}

	// 计算父节点的hash值
	parent.hash = calHash(append(left.hash, right.hash...))
	return parent
}

// 打印Merkle树
func (node *MerkleNode) PrintTree(indent int) {
	if node == nil {
		return
	}

	// 打印当前节点的hash值
	fmt.Printf("%sHash: %x\n", getIndent(indent), node.hash)

	// 递归打印左子树
	if node.leftChild != nil {
		fmt.Printf("%sLeft:\n", getIndent(indent))
		node.leftChild.PrintTree(indent + 1)
	}

	// 递归打印右子树
	if node.rightChild != nil {
		fmt.Printf("%sRight:\n", getIndent(indent))
		node.rightChild.PrintTree(indent + 1)
	}
}

// 获取缩进字符串
func getIndent(indent int) string {
	return fmt.Sprintf("%*s", indent*4, "")
}
